package com.imooc.controller;


import com.imooc.base.BaseInfoProperties;
import com.imooc.bo.RegistLoginBo;
import com.imooc.grace.result.GraceJSONResult;
import com.imooc.grace.result.ResponseStatusEnum;
import com.imooc.pojo.Users;
import com.imooc.service.UsersService;
import com.imooc.utils.IPUtil;
import com.imooc.utils.SMSUtils;
import com.imooc.vo.UsersVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.UUID;

@Slf4j
@RequestMapping("passport")
@RestController
@Api(tags = "短信发送")
public class PassportController extends BaseInfoProperties {
        @Autowired
       private   SMSUtils smsUtils;

        @Autowired
        private UsersService usersService;

        @PostMapping("getSMSCode")
        public GraceJSONResult getSMSCode(@RequestParam String mobile, HttpServletRequest request) throws Exception {
            if(StringUtils.isBlank(mobile)){
                return GraceJSONResult.ok();
            }
            // 获得用户ip，
            String userIp = IPUtil.getRequestIp(request);
            // 根据用户ip进行限制，限制用户在60秒之内只能获得一次验证码
            redis.setnx60s(MOBILE_SMSCODE+":"+userIp,userIp);
            String code = (int)((Math.random() * 9 + 1) * 100000) + "";
            smsUtils.sendSMS(mobile,code);
            //验证码存入redis中 用于后续验证
            redis.set(MOBILE_SMSCODE+":"+mobile,code,60*30);
            log.info(code);
            return GraceJSONResult.ok();
        }
        @PostMapping("login")
        public GraceJSONResult login(@Valid @RequestBody RegistLoginBo registLoginBo){
            //判断是否有错误信息 有则返回给前端
//            if (result.hasErrors()){
//                Map<String, String> map = getErrors(result);
//              return   GraceJSONResult.errorMap(map);
//            }
            String mobile = registLoginBo.getMobile();
            String smsCode = registLoginBo.getSmsCode();
            String  redisCode = redis.get(MOBILE_SMSCODE + ":" + mobile);//取出redis 存放的code
            //判断验证码
            if (StringUtils.isBlank(redisCode) ||  !redisCode.equalsIgnoreCase(smsCode)  ){//和前端传入的code 进行比较
                return GraceJSONResult.errorCustom(ResponseStatusEnum.SMS_CODE_ERROR);
            }

            //查询用户是否存在
            Users user = usersService.queryMobileIsExist(mobile);
            if(user == null){
                // 如果没有该用户就创建用户
                usersService.createUsers(mobile);
            }
            //如果有 则保存用户会话信息
            String UToken = UUID.randomUUID().toString();
            redis.set(REDIS_USER_TOKEN+":"+ user.getId(),UToken);
            //用户注册后 删除redis中的验证码
            redis.del(MOBILE_SMSCODE + ":" + mobile);
            //返回前端用户信息 包含会话信息
            UsersVo usersVo = new UsersVo();
            BeanUtils.copyProperties(user,usersVo);
            usersVo.setUserToken(UToken);

            return GraceJSONResult.ok(usersVo);
        }
        @PostMapping("logout")
        public GraceJSONResult logout(@RequestParam String userId){
            // 后端只需要清除用户的token信息即可 前端也需要清除 清除本地的app中的用户信息和token
                redis.del(REDIS_USER_TOKEN+":"+ userId);
                return  GraceJSONResult.ok();
        }

}
